package com.hsteach.web.controller.rota;

import com.google.common.collect.Maps;
import com.hsteach.common.annotation.Anonymous;
import com.hsteach.common.config.AppConfig;
import com.hsteach.common.core.controller.BaseController;
import com.hsteach.common.core.domain.AjaxResult;
import com.hsteach.common.core.page.TableDataInfo;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.common.utils.poi.ExcelUtil;
import com.hsteach.dao.domain.rota.Rota;
import com.hsteach.dao.domain.rota.RotaDetail;
import com.hsteach.enums.BooleanEnum;
import com.hsteach.enums.DutyRoleEnum;
import com.hsteach.service.rota.RotaDetailService;
import com.hsteach.service.rota.RotaService;
import com.hsteach.web.controller.rota.dto.AddRotaPersonDto;
import com.hsteach.web.controller.rota.dto.ListRotaDetailDto;
import com.hsteach.web.controller.rota.vo.ListRotaDetailExcel;
import com.hsteach.web.controller.rota.vo.ListRotaDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 值班日期明细Controller
 * 
 * @author fanxquer
 * @date 2023-10-18
 */
@Api(value = "值班明细管理", tags = "值班明细管理")
@RestController
@RequestMapping("/rota/detail")
public class RotaDetailController extends BaseController
{
    @Autowired
    private RotaDetailService rotaDetailService;

    @Autowired
    private RotaService rotaService;

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private AppConfig appConfig;

    /**
     * 查询值班日期明细列表
     */
    @ApiOperation("查询值班日期明细")
    @GetMapping("/list")
    public TableDataInfo list(ListRotaDetailDto dto)
    {
        List<ListRotaDetailVo> list = rotaDetailService.selectRotaDetailList(dto);
        return getDataTable(list);
    }

    /**
     * 查询我能看到的值班日期明细
     */
    @ApiOperation("查询我能看到的值班日期明细（未归档）")
    @GetMapping("/listMine")
    public TableDataInfo listMine(ListRotaDetailDto dto)
    {
        Rota rota = rotaService.selectRotaById(dto.getRotaId());
        if (BooleanEnum.TRUE.getCode().equals(rota.getFileFlg())) {
            throw new ServiceException("值班表已归档");
        }
        dto.setFileFlg(BooleanEnum.FALSE.getCode());
        List<ListRotaDetailVo> list = rotaDetailService.selectRotaDetailList(dto);
        return getDataTable(list);
    }

    /**
     * 导出值班日期明细列表
     */
    @Anonymous
    @ApiOperation("下载值班表模板")
    @GetMapping("/download/template")
    public AjaxResult export(HttpServletResponse response)
    {
        String templateUrl = appConfig.getConfig().get(SecurityUtils.getAuthInfo().getAppId()).getTemplateUrl();
        AjaxResult success = AjaxResult.success();
        Map<String, String> data = Maps.newHashMap();
        data.put("url", templateUrl);
        success.put("data", data);
        return success;
    }

    @ApiOperation("导出值班表")
    @GetMapping("/export")
    public void export(HttpServletResponse response, ListRotaDetailDto dto) {
        List<ListRotaDetailVo> list = rotaDetailService.selectRotaDetailList(dto);
        List<ListRotaDetailExcel> excels = list.stream().map(e -> {
            ListRotaDetailExcel excel = new ListRotaDetailExcel();
            excel.setDutyDate(e.getDutyDate());
            excel.setLeaders(e.getRotaPersons().stream().filter(k -> DutyRoleEnum.LEADER.getCode().equals(k.getDutyRole())).map(k -> Optional.ofNullable(k.getPersonName()).orElse("")).collect(Collectors.joining("、")));
            excel.setLeaderPhones(e.getRotaPersons().stream().filter(k -> DutyRoleEnum.LEADER.getCode().equals(k.getDutyRole())).map(k -> Optional.ofNullable(k.getPersonMobile()).orElse("")).collect(Collectors.joining("、")));
            excel.setPersons(e.getRotaPersons().stream().filter(k -> DutyRoleEnum.PERSON.getCode().equals(k.getDutyRole())).map(k -> Optional.ofNullable(k.getPersonName()).orElse("")).collect(Collectors.joining("、")));
            excel.setPersonPhones(e.getRotaPersons().stream().filter(k -> DutyRoleEnum.PERSON.getCode().equals(k.getDutyRole())).map(k -> Optional.ofNullable(k.getPersonMobile()).orElse("")).collect(Collectors.joining("、")));
            return excel;
        }).collect(Collectors.toList());
        ExcelUtil<ListRotaDetailExcel> util = new ExcelUtil<ListRotaDetailExcel>(ListRotaDetailExcel.class);
        util.exportExcel(response, excels, "值班日期明细");
    }

    @ApiOperation("导入值班表")
    @PostMapping("/import/{id}")
    public AjaxResult uploadFile(@PathVariable("id") Long id, MultipartFile file) throws Exception {
        return rotaDetailService.importFile(id, file.getInputStream());
    }


    /**
     * 新增值班人员
     */
    @ApiOperation("新增值班人员")
    @PostMapping("/person")
    public AjaxResult add(@RequestBody AddRotaPersonDto dto)
    {
        return toAjax(rotaDetailService.addRotaPerson(dto));
    }

    /**
     * 删除值班人员
     */
    @ApiOperation("删除值班人员")
    @DeleteMapping("/person/{id}")
    public AjaxResult removePerson(@PathVariable Long id)
    {
        return toAjax(rotaDetailService.removePerson(id));
    }

}
